using System;using System.Threading;using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog;

namespace DnsService.Services
{
    /// <summary>
    /// Windows服务实现类，用于将DNS服务作为Windows系统服务运行
    /// 作者：huobing
    /// </summary>
    public class LocalDnsWindowsService : IHostedService
    {
        private readonly DnsServiceManager _dnsServiceManager;
        private readonly Logger _logger = LogManager.GetCurrentClassLogger();
        private CancellationTokenSource? _cancellationTokenSource;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dnsServiceManager">DNS服务管理器</param>
        public LocalDnsWindowsService(DnsServiceManager dnsServiceManager)
        {
            _dnsServiceManager = dnsServiceManager ?? throw new ArgumentNullException(nameof(dnsServiceManager));
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>任务</returns>
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.Info("Windows服务启动中...");
            _cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            // 在单独的线程中启动DNS服务
            Task.Run(() =>
            {
                try
                {
                    var options = new DnsServiceOptions();
                    _dnsServiceManager.Run(options);
                }
                catch (System.Exception ex)
                {
                    _logger.Error($"DNS服务运行异常: {ex.Message}", ex);
                }
            }, _cancellationTokenSource.Token);

            _logger.Info("Windows服务启动完成");
            return Task.CompletedTask;
        }

        /// <summary>
        /// 停止服务
        /// </summary>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>任务</returns>
        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.Info("Windows服务停止中...");
            
            // 取消正在运行的任务
            _cancellationTokenSource?.Cancel();
            
            // 停止DNS服务
            _dnsServiceManager.StopService();
            
            _logger.Info("Windows服务已停止");
            return Task.CompletedTask;
        }
    }
}